package com.cyt.chattlibrary.face;

import android.content.Context;
import android.graphics.Color;
import android.support.annotation.NonNull;
import android.support.v4.view.PagerAdapter;
import android.text.Editable;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.style.ImageSpan;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.RelativeLayout;

import com.cyt.chattlibrary.R;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class FaceViewPager extends IndicatorViewPager {
    //	private int[] imageIds = new int[105]
    private ArrayList<Integer> imageIds = new ArrayList<>();
    //    private Handler handler;
    private String[] imageRes;
    private EditText text;

    public FaceViewPager(Context context, AttributeSet attrs) {
        super(context, attrs);
        imageRes = getResources().getStringArray(R.array.default_smiley_names);

        List<List<Map<String, Object>>> emotionListList = separateData();
        setAdapter(new GridViewAdapter(emotionListList));
        setCurrentItem(0);
        setBackgroundColor(Color.WHITE);

    }

    private List<List<Map<String, Object>>> separateData() {
        int pageSize = 20;
        int size = imageRes.length;
        int pageCount = size / pageSize;
        List<List<Map<String, Object>>> emotionListList = new ArrayList<>();
        for (int i = 0; i < pageCount; i++) {
            List<Map<String, Object>> listItems = new ArrayList<>();
            for (int t = i * 20; t < Math.min((i + 1) * 20, size); t++) {
                try {

                    Field filed = R.drawable.class.getDeclaredField(imageRes[t]);
                    int resourceId = Integer.parseInt(filed.get(null).toString());
                    imageIds.add(resourceId);
                    Map<String, Object> listItem = new HashMap<>();
                    listItem.put("image", resourceId);
                    listItems.add(listItem);

                } catch (SecurityException | IllegalArgumentException | IllegalAccessException | NoSuchFieldException e) {
                    e.printStackTrace();
                }
            }
            Map<String, Object> listItem = new HashMap<>();
            listItem.put("image", R.drawable.btn_del_selector);
            listItems.add(listItem);
            emotionListList.add(listItems);
        }
        return emotionListList;
    }

    public EditText getEditText() {
        return text;
    }

    public void setEditText(EditText editText) {
        this.text = editText;
    }


    private class GridViewAdapter extends PagerAdapter {

        private List<List<Map<String, Object>>> emotionListList;

        private GridViewAdapter(List<List<Map<String, Object>>> emotionListList) {
            this.emotionListList = emotionListList;
        }


        @Override
        public int getCount() {
            return emotionListList.size();
        }

        @NonNull
        @Override
        public Object instantiateItem(@NonNull ViewGroup container, final int position) {

            RelativeLayout relativeLayout = new RelativeLayout(container.getContext());
            relativeLayout.setGravity(Gravity.CENTER);
            EmotionGrid gridView = new EmotionGrid(container.getContext());
            gridView.bindData(emotionListList.get(position));
            ViewGroup.LayoutParams layoutParams = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
            gridView.setLayoutParams(layoutParams);
            relativeLayout.addView(gridView);
            container.addView(relativeLayout);
            gridView.setOnItemClickListener((arg0, arg1, arg2, arg3) -> {
                if (text == null)
                    return;
                int index = position * 20 + arg2;
                if (arg2 < 20) {
                    ImageSpan imageSpan = EmotionManager.getImageSpan(getContext(), imageIds.get(index % imageIds.size()), text.getTextSize());
                    String str = imageRes[index % imageRes.length];

                    SpannableString spannableString = new SpannableString(str);
                    spannableString.setSpan(imageSpan, 0, 4, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                    Editable content = text.getText();
                    int start = text.getSelectionStart();
                    content.insert(start, spannableString);
                    text.setText(content);
                    text.setSelection(start + spannableString.length());
                } else {
                    del(text);
                }
            });
            return relativeLayout;
        }

        void del(EditText text) {
            KeyEvent event = new KeyEvent(0, 0, 0, KeyEvent.KEYCODE_DEL, 0, 0, 0, 0, KeyEvent.KEYCODE_ENDCALL);
            text.dispatchKeyEvent(event);
        }

        @Override
        public void destroyItem(@NonNull ViewGroup collection, int position, @NonNull Object view) {
            collection.removeView((View) view);
        }

        @Override
        public boolean isViewFromObject(@NonNull View arg0, @NonNull Object arg1) {
            // TODO Auto-generated method stub
            return arg0 == arg1;
        }


    }
}
